package com.crealth.thread;

import java.io.FileInputStream;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import com.alibaba.fastjson.JSONObject;
import com.crealth.Config;
import com.crealth.ConstantDefine;
import com.crealth.db.MyselfClienteleDb;
import com.crealth.handler.ResponseMsgQueue;
import com.crealth.manager.ClienteleInfoManager;
import com.crealth.model.ClienteleInfoModel;
import com.crealth.model.UserModel;
import com.crealth.msg.NetMessageData;
import com.crealth.utils.PhoneNumDecode;
import com.crealth.utils.Utils;



public class ImportClienteleDetailThread extends Thread {
	
	private static Logger logger = Logger.getLogger("running_log");
	private static Logger errorLog = Logger.getLogger("error_log");
	
	private String importFileName;
	private UserModel userObj;
	private JSONObject fieldMapJson;
	
	
	public ImportClienteleDetailThread(String fileName, UserModel user) {
		importFileName = fileName;
		userObj = user;
		fieldMapJson = null;
	}
	
	public void setFieldMapJson(JSONObject setJson) {
		fieldMapJson = setJson;
	}
	
	@Override
	public void run() {		
		importMobi();
	}
	
	private void importMobi() {
		logger.info("import clientele thread start......");
		int userID = userObj.getId();
		Sheet sheet;
        Workbook book;
        Cell curCell;
        try {
        	String strFileName = "./uploadData/" + importFileName;
        	InputStream is = new FileInputStream(strFileName);      	
            book = WorkbookFactory.create(is);
            if (book == null) {
            	errorLog.error(strFileName + "book is null");
            	return;
            }            
            sheet = book.getSheetAt(0);
            int nCol = 0;           
            int nRow = 0;
            if (sheet == null || sheet.getLastRowNum() < 2) {
            	errorLog.error(strFileName + "sheet is null");
            	return;
            }
            List<ClienteleInfoModel> cliModels = new ArrayList<ClienteleInfoModel>();
            List<String> titlels = new ArrayList<String>();
            Row rowObj = sheet.getRow(0);
            int colSum = rowObj.getLastCellNum();
            int rowSum = sheet.getLastRowNum();
            String strValue = "";           
            for (nCol = 0; nCol < colSum; ++nCol) {
            	curCell = rowObj.getCell(nCol);
            	if (curCell == null) {
            		break;
            	}
            	strValue = curCell.toString().trim();
            	if (strValue.length() == 0) {
            		break;
            	}
            	titlels.add(strValue);
            }
            sendProgressMsg(0, rowSum-1);
            int importNum = 0;
            for (nRow = 1; nRow < rowSum; ++nRow) {
            	rowObj = sheet.getRow(nRow);
            	ClienteleInfoModel clienteleInfo = new ClienteleInfoModel();
            	int findFieldNum = 0;
                for (nCol = 0; nCol < colSum; ++nCol ) {
                	if (nCol >= titlels.size()) {
                		break;
                	}
                	String title = titlels.get(nCol);
                	curCell = rowObj.getCell(nCol);
                	if (curCell == null) {
                		break;
                	}
                	strValue = curCell.toString().trim();                	
                	if (fieldMapJson == null) {  //  模板字段方式导入
	                	if (title.equals("Date")) {
	                		clienteleInfo.setInputDate(strValue);
	                	} else if (title.equals("Type")) {
	                		clienteleInfo.setType(strValue);
	                	} else if (title.equals("Name") || title.equals("姓名")) {
	                		clienteleInfo.setName(strValue);
	                	} else if (title.equals("手机") || title.equals("Mobi") || 
	                			title.equals("手机号") || title.equals("手机号码")) {
	                		if (strValue.startsWith("1.") || strValue.indexOf('E') > 0) {
	                    		strValue = doublePhoneNumToString(strValue);
	                    	}
	                		if (strValue.length() != 11) {
	                			break;
	                		}
	                		if (Config.mobiPhoneEncrypt) {                        	
	                			strValue = PhoneNumDecode.encryptPhone(strValue);
	                        }
	                		clienteleInfo.setMobi(strValue);
	                	} else if (title.equals("Noti") || title.equals("图片名")) {				
	                		clienteleInfo.setNoti(strValue);
	    				}
	    				else if (title.equals("Tele")) {
	    					clienteleInfo.setTele(strValue);
	    				} else if (title.equals("Hous")) {
	    					clienteleInfo.setHous(strValue);
	    				} else if (title.equals("Addr") || title.equals("地址")) {
	    					clienteleInfo.setAddr(strValue);
	    				} else if (title.equals("Unit") || title.equals("单位")) {
	    					clienteleInfo.setUnit(strValue);
	    				}
	    				else if (title.equals("Dscr") || title.equals("memo") || title.equals("备注") ) {
	    					clienteleInfo.setDscr(strValue);
	    				}
	    				else if (title.equals("IdNo") || title.equals("身份证号")) {
	    					clienteleInfo.setIdNo(strValue);
	    				}
                	} else {  //  关联字段映射  导入
                		if (fieldMapJson.containsKey("Date") && title.equals(fieldMapJson.get("Date")) ) {
	                		clienteleInfo.setInputDate(strValue);
	                		findFieldNum++;
	                	} else if (fieldMapJson.containsKey("Type") && title.equals(fieldMapJson.get("Type")) ) {
	                		clienteleInfo.setType(strValue);
	                		findFieldNum++;
	                	} else if (fieldMapJson.containsKey("Name") && title.equals(fieldMapJson.get("Name") )
	                			|| fieldMapJson.containsKey("姓名") && title.equals(fieldMapJson.get("姓名")) ) {
	                		clienteleInfo.setName(strValue);
	                		findFieldNum++;
	                	} else if (fieldMapJson.containsKey("手机") && title.equals(fieldMapJson.get("手机")) || 
	                			fieldMapJson.containsKey("手机号") && title.equals(fieldMapJson.get("手机号")) || 
	                			fieldMapJson.containsKey("Mobi") && title.equals(fieldMapJson.get("Mobi")) ) {
	                		if (strValue.length() != 11) {
	                			break;
	                		}
	                		if (Config.mobiPhoneEncrypt) {                        	
	                			strValue = PhoneNumDecode.encryptPhone(strValue);
	                        }
	                		clienteleInfo.setMobi(strValue);
	                		findFieldNum++;
	                	} else if (fieldMapJson.containsKey("Noti") && title.equals(fieldMapJson.get("Noti")) || 
	                			fieldMapJson.containsKey("图片名") && title.equals(fieldMapJson.get("图片名")) ) {				
	                		clienteleInfo.setNoti(strValue);
	                		findFieldNum++;
	    				}
	    				else if (fieldMapJson.containsKey("Tele") && title.equals(fieldMapJson.get("Tele")) ) {
	    					clienteleInfo.setTele(strValue);
	    					findFieldNum++;
	    				} else if (fieldMapJson.containsKey("Hous") && title.equals(fieldMapJson.get("Hous")) ) {
	    					clienteleInfo.setHous(strValue);
	    					findFieldNum++;
	    				} else if (fieldMapJson.containsKey("Addr") && title.equals(fieldMapJson.get("Addr")) || 
	    						fieldMapJson.containsKey("地址") && title.equals(fieldMapJson.get("地址")) ) {
	    					clienteleInfo.setAddr(strValue);
	    					findFieldNum++;
	    				} else if (fieldMapJson.containsKey("Unit") && title.equals(fieldMapJson.get("Unit")) || 
	    						fieldMapJson.containsKey("单位") && title.equals(fieldMapJson.get("单位")) ) {
	    					clienteleInfo.setUnit(strValue);
	    					findFieldNum++;
	    				}
	    				else if (fieldMapJson.containsKey("Dscr") && title.equals(fieldMapJson.get("Dscr")) || 
	    						fieldMapJson.containsKey("memo") && title.equals(fieldMapJson.get("memo")) || 
	    						fieldMapJson.containsKey("备注") && title.equals(fieldMapJson.get("备注")) ) {
	    					clienteleInfo.setDscr(strValue);
	    					findFieldNum++;
	    				}
	    				else if (fieldMapJson.containsKey("IdNo") && title.equals(fieldMapJson.get("IdNo")) ) {
	    					clienteleInfo.setIdNo(strValue);
	    					findFieldNum++;
	    				}
                		
                		if (findFieldNum >= fieldMapJson.size()) {
                			break;
                		}
                	}
                }
               
                String mobi = clienteleInfo.getMobi();
                if (mobi.length() != 11) {
                	continue;
                }
                clienteleInfo.setCreaterUserID(userID);
                cliModels.add(clienteleInfo);
                importNum++;
                if (importNum % 10 == 0) {
            		sendProgressMsg(importNum, rowSum-1);
            	}
            }
            book.close();
            sendProgressMsg(importNum, rowSum-1);
            if (cliModels.size() > 0) {
            	if ( userObj.getPosition() >= ConstantDefine.Branch_Mgr_Fu ) {
		    		ClienteleInfoManager.addClienteleModel(cliModels);
		    		ClienteleInfoManager.initMaxID();
            	} else {
            		MyselfClienteleDb.deleteClienteleByCreateID(userID);
            		MyselfClienteleDb.addClienteleModel(userID, cliModels);
            	}
            }
            
            Utils.deleteFile(strFileName);
        } catch(Exception e) {
        	errorLog.error("", e);
        }
	}
	
	private void sendProgressMsg(int curNum, int sumNum) {
		NetMessageData sendMsg = new NetMessageData();
		sendMsg.setMsgCmd(NetMessageData.Net_Import_Clientele_Detail);
		JSONObject resJson = new JSONObject();
		int userID = userObj.getId();
		resJson.put("resCode", 0);
		resJson.put("curNum", curNum);
		resJson.put("sumNum", sumNum);
        sendMsg.setMsgBody(resJson.toJSONString());
        ResponseMsgQueue.addMsgToQueue(NetMessageData.Net_Import_Clientele_Detail, 
        		userID, sendMsg);
	
	}
	
	//  Execl 手机号码  科学计数法  转 字符串的手机号码
	public static String doublePhoneNumToString(String dPhoneNum) {
		if (dPhoneNum == null || dPhoneNum.length() < 10) {
			return "";
		}
		dPhoneNum = dPhoneNum.trim();
		int eIndex = dPhoneNum.indexOf('E');
		if (!dPhoneNum.startsWith("1.") || eIndex < 0) {
			return "";
		}
		String strNum = dPhoneNum.substring(0, eIndex);
		int weishu = Integer.parseInt(dPhoneNum.substring(eIndex+1));
		if (strNum.length() > 0 && weishu > 0) {
			double tempd = Double.parseDouble(strNum);
			tempd = tempd * Math.pow(10, weishu);
			Double dou_obj = new Double(tempd);
	        NumberFormat nf = NumberFormat.getInstance();
	        nf.setGroupingUsed(false);
	        String dou_str = nf.format(dou_obj);
			return dou_str;
		}
		
		return "";
	}
	
	
}
